/*
 * Copyright 2011 Kim Lindhardt Madsen
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package dk.lindhardt.gwt.geie.client.edit;

import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.user.client.ui.Widget;
import dk.lindhardt.gwt.geie.client.Validator;
import dk.lindhardt.gwt.geie.shared.*;

import java.io.Serializable;
import java.util.List;

/**
 * User: AnAmuser
 * Date: 29-07-11
 * <p/>
 * Handles edit of number and number formula cells
 */
@SuppressWarnings({"GWTStyleCheck"})
public class NumberValueEditor implements ValueEditor {

   private Cell cell;
   private CellValueEditBox editBox;
   private EditHandler editHandler;

   /**
    * For testing
    */
   NumberValueEditor() {
   }

   public NumberValueEditor(EditHandler editHandler, Cell cell) {
      this.editHandler = editHandler;
      this.cell = cell;
      editBox = new CellValueEditBox();
      editBox.addValidator(new Validator() {
         public ValidateResponse validate() {
            if (!editBox.isFormula()) {
               try {
                  Double.parseDouble(editBox.getText());
                  return new ValidateResponse(Status.OK, "");
               } catch (NumberFormatException e) {
                  return new ValidateResponse(Status.FAIL, editBox.getText() + " is not a number");
               }
            }
            return new ValidateResponse(Status.OK, "");
         }
      });
   }

   public boolean isListeningForTableSelections() {
      return editBox.isFormula();
   }

   public void handleTableSelection(List<Cell> cells) {
      if (cells.size() == 1) {
         editBox.insertVariable(cells.get(0).getPosition());
         editBox.regainFocus();
      } else if (cells.size() > 1) {
         editBox.insertVariable(cells.get(0).getPosition());
         editBox.insertText(":");
         editBox.insertVariable(cells.get(cells.size() - 1).getPosition());
         editBox.regainFocus();
      }
   }

   public Cell createNewCell() {
      if (editBox.isFormula()) {
         Formula formula = FormulaConverter.convertString(editBox.getText().substring(1));
         return new NumberFormulaCell(formula, cell.getPosition(), cell.getCellFormatKey());
      } else {
         try {
            double value = Double.parseDouble(editBox.getText());
            return new NumberCell(value, cell.getPosition(), cell.getCellFormatKey());
         } catch (NumberFormatException e) {
            return new ErrorCell(editBox.getText(), editBox.getText() + " is not a number", cell);
         }
      }
   }

   public boolean validate() {
      return editBox.validate();
   }

   public Widget getInputWidget() {
      editBox.addKeyDownHandler(
            new KeyDownHandler() {
               public void onKeyDown(KeyDownEvent event) {
                  int code = event.getNativeKeyCode();
                  if (KeyCodes.KEY_ENTER == code) {
                     editHandler.onEditConfirmed();
                  }
               }
            });
      return editBox.asWidget();
   }

   public void setInitialInputValue(Serializable value) {
      editBox.setValue(value);
   }

}
